package com.zwr.sheller.shop.service.impl;

import com.zwr.sheller.core.pojo.DeliveryManagement;
import com.zwr.sheller.core.util.JsonUtil;
import com.zwr.sheller.core.util.ThreadLocalUtil;
import com.zwr.sheller.shop.mapper.DeliveryManagementMapper;
import com.zwr.sheller.shop.service.DeliveryManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Map;

/**
 * @Author LSY
 * @Date 2022/1/11 8:49
 * @Version 1.0
 **/
@Service
public class DeliveryManagementServiceImpl implements DeliveryManagementService {

    DeliveryManagementMapper deliveryManagementMapper;
    @Autowired(required = false)
    public DeliveryManagementServiceImpl(DeliveryManagementMapper deliveryManagementMapper) {
        this.deliveryManagementMapper = deliveryManagementMapper;
    }

    @Override
    public void alterUnifiedDeliveryStatus() {
        DeliveryManagement deliveryManagement = findThisDeliveryDeliveryManagement();

        deliveryManagement.setIsUnified(!deliveryManagement.getIsUnified());
        deliveryManagementMapper.updateByPrimaryKeySelective(deliveryManagement);
    }

    @Override
    public void alterMerchantDeliveryStatus() {
        DeliveryManagement deliveryManagement = findThisDeliveryDeliveryManagement();

        deliveryManagement.setIsMerchantDelivery(!deliveryManagement.getIsMerchantDelivery());
        deliveryManagementMapper.updateByPrimaryKeySelective(deliveryManagement);
    }

    @Override
    public void setUnifiedDeliveryCost(Double cost) {
        DeliveryManagement deliveryManagement = findThisDeliveryDeliveryManagement();

        deliveryManagement.setUnifiedDeliveryCost(cost);
        deliveryManagementMapper.updateByPrimaryKeySelective(deliveryManagement);
    }

    @Override
    public void setMerchantDeliveryCost(Double cost) {
        DeliveryManagement deliveryManagement = findThisDeliveryDeliveryManagement();

        deliveryManagement.setMerchantDeliveryCost(cost);
        deliveryManagementMapper.updateByPrimaryKeySelective(deliveryManagement);
    }

    @Override
    public void setMerchantDeliveryArea(Integer region) {
        DeliveryManagement deliveryManagement = findThisDeliveryDeliveryManagement();

        deliveryManagement.setRegion(region);
        deliveryManagementMapper.updateByPrimaryKeySelective(deliveryManagement);
    }

    private DeliveryManagement findThisDeliveryDeliveryManagement() {
        Map<String, Object> map = JsonUtil.stringToObject(String.valueOf(ThreadLocalUtil.getObject()), Map.class);
        Long merchantId = Long.parseLong(String.valueOf(map.get("merchantId")));

        Example example = new Example(DeliveryManagement.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        return deliveryManagementMapper.selectByExample(example).get(0);
    }
}
